# -*- coding: utf-8 -*-
from django import forms

from google.appengine.ext.db import djangoforms
from base.models import School, ClassProperty
from base.util.decorators import render_to, login_required, admin_required
import logging

@login_required
@render_to('classproperty/list.html')
def list(request, school_id):
    school = School.get_using_id(int(school_id))
    query = ClassProperty.gql('WHERE school=:1', school.key())
    classproperties = query.fetch(10)
    return {'classproperties': classproperties}

class ClassPropertyForm(djangoforms.ModelForm):
    class Meta:
        model = ClassProperty

#    def clean(self):
#        pass
#        cleaned_data = self.cleaned_data
#        name = cleaned_data.get('name')
#        if School.is_existed(name):
#            raise forms.ValidationError(u'You already have the same school\'s name')
#        return cleaned_data

@admin_required
@render_to('classproperty/form.html')
def create(request, school_id):
    school = School.get_using_id(int(school_id))
    form = ClassPropertyForm(initial={'school': school.key()})
    if request.method == 'POST':
        form = ClassPropertyForm(request.POST)
        if form.is_valid():
            classproperty = form.save(commit=False)
            classproperty.put()
            return classproperty.get_absolute_url
    return {'form': form}

@admin_required
@render_to('classproperty/detail.html')
def detail(request, classproperty_id):
    classproperty = ClassProperty.get_using_id(int(classproperty_id))
    return {'classproperty': classproperty}

@admin_required
@render_to('classproperty/form.html')
def change(request, classproperty_id):
    classproperty = ClassProperty.get_using_id(int(classproperty_id))
    form = ClassPropertyForm(request.POST or None, instance=classproperty)
    if form.is_valid():
        classproperty = form.save()
        return classproperty.get_absolute_url
    return {'form': form}